<?

$_table = 'CR_CLASSIFICATOR_VALUE o';
$_parent_key = 'classificatorvalue_id';

$_magic = "classificator_id=1 AND state='A' AND onsite=1";

$_min_length = 2;
$_res_num = 16;

$res = array('query' => trim(postdata('q')), 'suggestions' => array(), 'data' => array());

if ($q = search_safe(mb_strtoupper(trim(postdata('q'))))) {
	
//dbdebug();
	
	if (mb_strlen($q) >= $_min_length)

		if (sizeof($d = datafetch_array('db_list', 
			array('table' => $_table, 'index' => 'id', 
				'where' => "$_magic AND upper(name) LIKE '$q%'", 
				'order' => 'name',
				'select' => "id, name, $_parent_key parent_id", 
				'limit' => $_res_num)))) {
				
			$parents = array(); foreach($d as $v) if ($v['parent_id']) $parents[] = $v['parent_id'];
			$keys = implode(',', $parents);
			$parents = datafetch_array('db_list', 
				array('table' => $_table, 
					'index' => 'id', 
					'where' => "id IN ($keys)", 
					'select' => 'id, name'));
						
			foreach($d as $v) {
				$res['data'][] = $v['id'];
				$t = $v['name'];
				if (($p = $v['parent_id']) && isset($parents[$p]))
					$t .= ' <span>'.h($parents[$p]['name']).'</span>';
				$res['suggestions'][] = $t;
			}
		}
}

print json_encode($res);
exit;